<?php
namespace app\know\validate;

use app\know\model\GrammarModel;
use think\Validate;
use think\facade\Log;

class GrammarValidate extends Validate
{
    protected $rule = [
        'chapter_uuid' => 'require|length:32',
		'content' => 'require|min:1|checkName|checkContentRepeat',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'chapter_uuid.require' => '章节ID为必填项',
        'chapter_uuid.length' => '章节ID不能为空',		
        'content.require' => '生词为必填项',
        'content.min' => '生词不能为空',
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['chapter_uuid', 'content'],
        'edit' => ['id', 'content'],
        'delete' => ['id'],
    ];

    protected function checkContentRepeat($value, $rule, $data)
    {
        if ($this->currentScene != 'edit') 
        {
            return true;
        }

        $model = new GrammarModel();
        $item  = $model->where('chapter_uuid', $data['chapter_uuid'])
                        ->where('id', '<>', $data['id'])
                        ->where('content', $data['content'])
                        ->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            Log::debug(__CLASS__ . __FUNCTION__ . $model->getLastSql());
            return $data['content'] . "---已经存在---";
        }
    }

    protected function checkName($value, $rule, $data)
    {
        if ($this->currentScene != 'add') 
        {
            return true;
        }

        $model = new GrammarModel();
        $item  = $model->where('chapter_uuid', $data['chapter_uuid'])
					   ->where('content', $data['content'])
                       ->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            Log::debug(__CLASS__ . __FUNCTION__ . $model->getLastSql());
            return $data['content'] . "---已经存在---";
        }
    }
}